namespace app\controller;

use think\Request;
use think\facade\Filesystem;
use app\model\Question as QuestionModel;

class Question
{
    // 添加/编辑题目
    public function save(Request $request)
    {
        $data = $request->post();
        $file = $request->file('image');
        
        // 处理图片上传
        if ($file) {
            $saveName = Filesystem::disk('public')->putFile('question', $file);
            $data['image'] = '/uploads/' . $saveName;
        }
        
        // 处理选项
        if (in_array($data['type'], [2,3])) {
            $options = [];
            foreach ($data['option_content'] as $k => $v) {
                $options[] = [
                    'id' => $k,
                    'text' => $v,
                    'image' => $data['option_image'][$k] ?? ''
                ];
            }
            $data['options'] = json_encode($options);
        }
        
        QuestionModel::saveData($data);
        return json(['code'=>0, 'msg'=>'操作成功']);
    }

    // 随机组卷
    public function randomPaper(Request $request)
    {
        $counts = $request->post('counts');
        $paperData = [
            'title' => $request->post('title'),
            'mode' => $request->post('mode'),
            'duration' => $request->post('duration'),
        ];
        
        $questionIds = [];
        foreach ($counts as $type => $count) {
            $ids = QuestionModel::where('type', $type)
                ->orderRaw('RAND()')
                ->limit($count)
                ->column('id');
            $questionIds = array_merge($questionIds, $ids);
        }
        
        $paperData['question_ids'] = implode(',', $questionIds);
        PaperModel::create($paperData);
        
        return json(['code'=>0, 'msg'=>'组卷成功']);
    }
}